import os

import chardet
import numpy as np
import cv2 as cv
import cv2
from PIL import Image
import sys
from matplotlib import pyplot as plt

def add_salt_noise(img, snr=0.5):
    # 指定信噪比
    SNR = snr
    # 获取总共像素个数
    size = img.size
    # 因为信噪比是 SNR ，所以噪声占据百分之10，所以需要对这百分之10加噪声
    noiseSize = int(size * (1 - SNR))
    # 对这些点加噪声
    for k in range(0, noiseSize):
        # 随机获取 某个点
        xi = int(np.random.uniform(0, img.shape[1]))
        xj = int(np.random.uniform(0, img.shape[0]))
        # 增加噪声
        if img.ndim == 2:
            img[xj, xi] = 255
        elif img.ndim == 3:
            img[xj, xi] = 0
    return img

path = 'D:/program/keras/save'


"""
腐蚀
cv2.erode(src,                     # 输入图像
	  kernel,                  # 卷积核
	  dst=None, 
	  anchor=None,
	  iterations=None,         # 迭代次数，默认1
	  borderType=None,
	  borderValue=None) 

膨胀
cv2.dilate(src,                    # 输入图像
           kernel,                 # 卷积核
           dst=None, 
           anchor=None, 
           iterations=None,        # 迭代次数，默认1
           borderType=None, 
           borderValue=None)
"""

def fushi_pz(path):
    imglist = os.listdir(path)
    for i in imglist:
        original_img = cv2.imread(os.path.join(path,i))
        res = cv2.resize(original_img, None, fx=0.6, fy=0.6,
                         interpolation=cv2.INTER_CUBIC)  # 图形太大了缩小一点
        B, G, R = cv2.split(res)  # 获取红色通道
        img = R
        _, RedThresh = cv2.threshold(img, 160, 255, cv2.THRESH_BINARY)
        # OpenCV定义的结构矩形元素
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        eroded = cv2.erode(RedThresh, kernel)  # 腐蚀图像
        dilated = cv2.dilate(RedThresh, kernel)  # 膨胀图像

        cv2.imshow("original_img", res)  # 原图像
        cv2.imshow("R_channel_img", img)  # 红色通道图
        cv2.imshow("RedThresh", RedThresh)  # 红色阈值图像
        cv2.imshow("Eroded Image", eroded)  # 显示腐蚀后的图像
        cv2.imshow("Dilated Image", dilated)  # 显示膨胀后的图像

        # NumPy定义的结构元素
        NpKernel = np.uint8(np.ones((3, 3)))
        Nperoded = cv2.erode(RedThresh, NpKernel)  # 腐蚀图像
        cv2.imshow("Eroded by NumPy kernel", Nperoded)  # 显示腐蚀后的图像
        cv2.waitKey()
        cv2.destroyAllWindows()


'''
for i in os.listdir(path):
    img = cv.imread(os.path.join(path,i), 1)
    img_salt = add_salt_noise(img, snr=0.99)
    imglist = []
    blured = cv.blur(img, (3, 3))
    blured1 = cv.blur(img, (7, 7))
    blured2 = cv.GaussianBlur(img, (3, 3), 0)
    blured3 = cv.GaussianBlur(img, (7, 7), 0)
    b1 = cv.medianBlur(img, 1)
    b2 = cv.medianBlur(img, 9)
    b3 = cv.bilateralFilter(img, 9, 5, 5)
    b4 = cv.bilateralFilter(img, 9, 50, 50)
    imglist = [blured,blured2,blured3,b1,b2,b3,b4]
    for j in imglist:
        cv2.imshow("1",j)
        cv2.waitKey()
        cv2.destroyAllWindows()

'''
fushi_pz(path)
